package com.lifp.exception.handler;

import com.lifp.vo.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2023/6/2
 * @Version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result bindingException(BindException e){
        //e.printStackTrace();

        List errors = new ArrayList<String>();

        List<ObjectError> allErrors = e.getAllErrors();
        // 遍历错误信息，返回给前端
        for (ObjectError error : allErrors) {
            errors.add(error.getDefaultMessage());
        }
        return Result.failed(errors.toString());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){
        //e.printStackTrace();
        return Result.failed(e.getMessage());
    }
}